package by.dkusch.aircompany.webapp.page.base.common;

import java.util.Iterator;

import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

import by.dkusch.aircompany.model.tables.base.BaseEntity;
import by.dkusch.aircompany.services.AbstractService;

public class EntityDataProvider<ID, Entity extends BaseEntity<ID>> extends SortableDataProvider<Entity, SingularAttribute<Entity, ?>> {

	private static final long serialVersionUID = 1L;

	private AbstractService<ID, Entity> service;

	public EntityDataProvider(AbstractService<ID, Entity> service) {
		super();
		this.service = service;
	}

	@Override
	public Iterator<? extends Entity> iterator(long first, long count) {
		if (getSort() != null) {
			SingularAttribute<Entity, ?> sortParam = getSort().getProperty();
			SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
			boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
			return service.getItemsWithOrder(sortParam, ascending, (int) first, (int) count).iterator();
		} else {
			return service.getItemsWithOrder(null, true, (int) first, (int) count).iterator();
		}
	}

	@Override
	public long size() {
		return service.getCount();
	}

	@Override
	public IModel<Entity> model(Entity entity) {
		return new CompoundPropertyModel<Entity>(entity);
	}

	// private List<Entity> filteredList()
}
